from django.shortcuts import render, redirect
from app01 import models


# Create your views here.
def depart_list(request):
    """部门列表"""
    # 1、从数据加载数据
    # qureyset类型=>列表[对象，对象，对象……]
    qureyset = models.Department.objects.all()

    return render(request, 'depart_list.html', {'qureyset': qureyset})


def depart_add(request):
    """添加部门"""
    # 1、处理请求
    if request.method == "GET":
        return render(request, 'depart_add.html')

    # 获取用户提交的POST请求（暂时不考虑title为空的情况，后面有简单方法处理）
    title = request.POST.get("title")

    # 2、保存到数据库
    models.Department.objects.create(title=title)

    # 3、重定向回到部门列表
    return redirect("/depart/list/")


def depart_delete(request):
    """删除部门"""
    # 1、获取id
    # 通过get请求得到url的参数实现删除http://127.0.0.1:8000/depart/delete/?nid=1
    nid = request.GET.get("nid")
    # 2、删除
    models.Department.objects.filter(id=nid).delete()
    # 3、重定向回到部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    """部门修改"""
    if request.method == "GET":
        # 根据nid，获取想要编辑的一行对象
        row_object = models.Department.objects.filter(id=nid).first()
        # print(row_object.id,row_object.title)
        return render(request, 'depart_edit.html', {"row_object": row_object})

    # 如果用户传递过来一个post请求
    # 1、获取用户提交的title
    title = request.POST.get("title")
    # 2、根据id到数据库中的数据进行更新
    # models.Department.objects.filter(id=nid).update(title=title,numbers = numbers,……)
    models.Department.objects.filter(id=nid).update(title=title)
    # 3、重定向用户列表
    return redirect("/depart/list/")


def user_list(request):
    """用户列表"""
    # 获取数据库表中的所有对象
    queryset = models.UserInfo.objects.all()
    """
    #测试获取内容--python语法
    for obj in queryset:
    print
    (
        obj.id,obj.name,obj.account,
        obj.create_time.strftime("%Y-%m-%d"),
        obj.get_gender_display(),
        obj.depart.title
    )
    """
    return render(request, 'user_list.html', {"queryset": queryset})


def old_user_add(request):
    """用户添加"""
    # 1、处理请求
    if request.method == "GET":
        return render(request, 'user_add.html')
    # 处理POST请求，获取表单
    name = request.POST.get("name")
    password = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("acc")
    create_time = request.POST.get("time")
    gender = request.POST.get("gen")
    depart_id = request.POST.get("depid")
    # 存到数据库
    models.UserInfo.objects.create(name=name, password=password, age=age,
                                   account=account, create_time=create_time,
                                   gender=gender, depart_id=depart_id)
    # 重定向回到部门列表
    return redirect("/user/list/")


def old_user_delete(request):
    """删除用户"""
    uid = request.GET.get("uid")
    models.UserInfo.objects.filter(id=uid).delete()
    return redirect("/user/list/")


def old_user_edit(request, uid):
    # 处理用户GET请求
    if request.method == "GET":
        row_object = models.UserInfo.objects.filter(id=uid).first()
        return render(request, 'user_edit.html', {"row_object": row_object})
    # 处理POST请求
    name = request.POST.get("name")
    password = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("acc")
    create_time = request.POST.get("time")
    gender = request.POST.get("gen")
    depart_id = request.POST.get("depid")
    # 修改数据表
    models.UserInfo.objects.filter(id=uid).update(name=name, password=password, age=age,
                                                  account=account, create_time=create_time,
                                                  gender=gender, depart_id=depart_id)
    # 重定向用户列表
    return redirect("/user/list/")


def user_add(request):
    """用户添加"""
    if request.method == "GET":
        context = {
            'gender_choice': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all(),
        }
        return render(request, 'user_add.html', context)
    # 获取用户提交的请求
    name = request.POST.get("name")
    password = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("acc")
    create_time = request.POST.get("time")
    gender = request.POST.get("gen")
    depart_id = request.POST.get("depid")
    # 存到数据库
    models.UserInfo.objects.create(name=name, password=password, age=age,
                                   account=account, create_time=create_time,
                                   gender=gender, depart_id=depart_id)
    # 重定向回到部门列表
    return redirect("/user/list/")


# ————————————————————————————————————————————————ModelForm实例————————————————————————————————————————————————
from django import forms

class UserModelForm(forms.ModelForm):
    #字段重构:编写验证规则
    name = forms.CharField(min_length=3,label="姓名")
    password = forms.CharField(min_length=6,label="密码")#validators:正则表达式，密码是6-18位数字
    # 重新定义ini方法
    def __init__(self, *args, **kwargs):
        # 引用父类的ini方法
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            # print(name,field)
            # if name == "password":
            # continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]
        # 样式标签
        # widgets = {
        # 输入框标签
        # "name":forms.TextInput(attrs={'class':'form-control'}),
        # "password":forms.PasswordInput(attrs={'class':'form-control'}),
        # ……
        # }


def user_model_add(request):
    """添加用户（ModelForm）"""
    if request.method == "GET":
        # 类实例化
        form = UserModelForm()
        return render(request, 'user_model_add.html', {'form': form})
    #处理POST请求并校验数据
    form = UserModelForm(data=request.POST)
    if form.is_valid():#校验成功
        #数据合法，保存数据
        #{'name': '小样', 'password': '111', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2022, 10, 1, 0, 0, tzinfo=<UTC>), 'gender': 2, 'depart': <Department: 人力部>}
        #print(form.cleaned_data)
        form.save()
        return redirect("/user/list/")
    #校验失败,在页面上显示错误信息
    #print(form.errors)
    return render(request, 'user_model_add.html', {'form': form})

def user_delete(request):
    """删除用户"""
    uid = request.GET.get("uid")
    models.UserInfo.objects.filter(id=uid).delete()
    return redirect("/user/list/")

def user_model_edit(request, nid):
    #获取当前行数据
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        #将默认值传递给页面
        form = UserModelForm(instance=row_object)
        return render(request, 'user_model_edit.html',{"form":form})
    #处理post请求
    form = UserModelForm(data=request.POST,instance=row_object)
    # 校验
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    return render(request,'user_model_edit.html',{"form":form})

